
#include <kernel/handle/handle.h>
#include <kernel/block/block.h>
#include <kernel/userid/userid.h>

#include <stdio.h>

userid ID;
handle Out, In, Error;

size device_unix_stdout (handle _h, const char *_name)
{	
	char *buf;
	size sz;

	sz = handle_stringlength (_h);

	buf = block_request (sz + 1);

	handle_read (_h, buf, sz);

	buf [sz] = '\0';

	printf ("%s", buf);

	block_release (buf);

	return sz;
}


size device_unix_stderr (handle _h, const char *_name)
{	
	char *buf;
	size sz;

	sz = handle_stringlength (_h);

	buf = block_request (sz + 1);

	handle_read (_h, buf, sz);

	buf [sz] = '\0';
	
	fprintf (stderr, "%s", buf);

	block_release (buf);

	return sz;
}

size device_unix_stdin (handle _h, const char *_name)
{
	char c;

	scanf ("%c", &c);

	handle_write (_h, &c, sizeof (char));

	return 1;
}


extern int user_device_unix_init ()
{
	handle kernelerror, kernelout;

	ID = userid_request ();
	
	Out = handle_request ("device.unix.stdout", ID);
	Error = handle_request ("device.unix.stderr", ID);
	In = handle_request ("device.unix.stdin", ID);

	handle_sink (Out, device_unix_stdout);
	handle_sink (Error, device_unix_stderr);
	handle_source (In, device_unix_stdin);


	kernelerror = handle_request ("kernel.error", ID);
	handle_sink (kernelerror, device_unix_stderr);

	kernelout = handle_request ("kernel.out", ID);
	handle_sink (kernelerror, device_unix_stderr);


	return 0;
}


extern int user_device_unix_cleanup ()
{
	handle_release (Out);
	handle_release (Error);
	handle_release (In);
}
